package com.situ.mall.web.controller;

import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.model.Product;
import com.mall.user.model.vo.LoginUserVO;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.ProductFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 搜索控制器
 */
@Slf4j
@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private ProductFeignService productFeignService;
    
    @Autowired
    private CategoryFeignService categoryFeignService;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 搜索页面
     */
    @GetMapping
    public String search(Model model,
                        @RequestParam(value = "q", required = false) String keyword,
                        @RequestParam(value = "categoryId", required = false) Long categoryId,
                        @RequestParam(value = "brandId", required = false) Long brandId,
                        @RequestParam(value = "minPrice", required = false) Double minPrice,
                        @RequestParam(value = "maxPrice", required = false) Double maxPrice,
                        @RequestParam(value = "sortBy", required = false) String sortBy,
                        @RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "size", defaultValue = "20") Integer size,
                        HttpServletRequest request) {
        
        try {
            // 获取分类树数据（用于筛选）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 如果有搜索关键词，记录搜索历史
            if (StringUtils.hasText(keyword)) {
                recordSearchHistory(keyword, request);
                recordHotKeyword(keyword);
            }

            // 搜索商品
            if (StringUtils.hasText(keyword) || categoryId != null || brandId != null) {
                JsonResult<Map<String, Object>> searchResult = productFeignService.getProducts(
                        keyword, brandId, categoryId, 1, null, page, size);
                
                if (searchResult != null && searchResult.getData() != null) {
                    Map<String, Object> data = searchResult.getData();
                    @SuppressWarnings("unchecked")
                    List<Product> products = (List<Product>) data.get("list");
                    Long total = (Long) data.get("total");
                    
                    model.addAttribute("products", products);
                    model.addAttribute("total", total);
                    model.addAttribute("totalPages", (int) Math.ceil((double) total / size));
                    
                    log.info("搜索结果: 关键词={}, 结果数={}", keyword, total);
                }
            }

            // 获取热门搜索关键词
            List<String> hotKeywords = getHotKeywords();
            model.addAttribute("hotKeywords", hotKeywords);
            
            // 获取用户搜索历史
            List<String> searchHistory = getUserSearchHistory(request);
            model.addAttribute("searchHistory", searchHistory);

            // 保存搜索条件
            model.addAttribute("keyword", keyword);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("brandId", brandId);
            model.addAttribute("minPrice", minPrice);
            model.addAttribute("maxPrice", maxPrice);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);

        } catch (Exception e) {
            log.error("搜索页面数据加载失败", e);
        }

        return "search-results"; // 需要创建这个模板
    }

    /**
     * 搜索建议 (AJAX自动完成)
     */
    @GetMapping("/suggest")
    @ResponseBody
    public JsonResult<?> searchSuggest(@RequestParam("q") String keyword) {
        try {
            if (!StringUtils.hasText(keyword) || keyword.length() < 2) {
                return JsonResult.success(Collections.emptyList());
            }

            // 基于关键词搜索商品名称（用于自动完成）
            JsonResult<Map<String, Object>> searchResult = productFeignService.getProducts(
                    keyword, null, null, 1, null, 1, 5);
            
            List<String> suggestions = new ArrayList<>();
            if (searchResult != null && searchResult.getData() != null) {
                Map<String, Object> data = searchResult.getData();
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) data.get("list");
                
                for (Product product : products) {
                    if (product.getName() != null && product.getName().toLowerCase().contains(keyword.toLowerCase())) {
                        suggestions.add(product.getName());
                    }
                }
            }

            // 添加热门搜索关键词
            List<String> hotKeywords = getHotKeywords();
            for (String hotKeyword : hotKeywords) {
                if (hotKeyword.toLowerCase().contains(keyword.toLowerCase()) && !suggestions.contains(hotKeyword)) {
                    suggestions.add(hotKeyword);
                }
            }

            // 限制返回数量
            if (suggestions.size() > 8) {
                suggestions = suggestions.subList(0, 8);
            }

            return JsonResult.success(suggestions);

        } catch (Exception e) {
            log.error("搜索建议获取失败: keyword={}", keyword, e);
            return JsonResult.success(Collections.emptyList());
        }
    }

    /**
     * 记录搜索历史
     */
    private void recordSearchHistory(String keyword, HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            String sessionId = request.getSession().getId();
            String key = currentUser != null ? 
                "search:history:user:" + currentUser.getId() : 
                "search:history:session:" + sessionId;
                
            // 获取现有历史
            @SuppressWarnings("unchecked")
            List<String> history = (List<String>) redisTemplate.opsForValue().get(key);
            if (history == null) {
                history = new ArrayList<>();
            }
            
            // 移除已存在的关键词并添加到开头
            history.remove(keyword);
            history.add(0, keyword);
            
            // 保持最多10条历史记录
            if (history.size() > 10) {
                history = history.subList(0, 10);
            }
            
            // 存储到Redis，7天过期
            redisTemplate.opsForValue().set(key, history, 7, TimeUnit.DAYS);
            
        } catch (Exception e) {
            log.warn("记录搜索历史失败: keyword={}", keyword, e);
        }
    }

    /**
     * 记录热门关键词
     */
    private void recordHotKeyword(String keyword) {
        try {
            String key = "search:hot:keywords";
            redisTemplate.opsForZSet().incrementScore(key, keyword, 1);
            // 设置7天过期
            redisTemplate.expire(key, 7, TimeUnit.DAYS);
        } catch (Exception e) {
            log.warn("记录热门关键词失败: keyword={}", keyword, e);
        }
    }

    /**
     * 获取热门搜索关键词
     */
    private List<String> getHotKeywords() {
        try {
            String key = "search:hot:keywords";
            Set<Object> hotKeywords = redisTemplate.opsForZSet().reverseRange(key, 0, 9);
            return new ArrayList<>(hotKeywords.stream().map(Object::toString).toList());
        } catch (Exception e) {
            log.warn("获取热门关键词失败", e);
            return List.of("手机", "电脑", "耳机", "数码相机", "平板电脑");
        }
    }

    /**
     * 获取用户搜索历史
     */
    private List<String> getUserSearchHistory(HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            String sessionId = request.getSession().getId();
            String key = currentUser != null ? 
                "search:history:user:" + currentUser.getId() : 
                "search:history:session:" + sessionId;
                
            @SuppressWarnings("unchecked")
            List<String> history = (List<String>) redisTemplate.opsForValue().get(key);
            return history != null ? history : new ArrayList<>();
            
        } catch (Exception e) {
            log.warn("获取搜索历史失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 清除搜索历史
     */
    @PostMapping("/clear-history")
    @ResponseBody
    public JsonResult<?> clearSearchHistory(HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            String sessionId = request.getSession().getId();
            String key = currentUser != null ? 
                "search:history:user:" + currentUser.getId() : 
                "search:history:session:" + sessionId;
                
            redisTemplate.delete(key);
            return JsonResult.success("搜索历史已清除");
            
        } catch (Exception e) {
            log.error("清除搜索历史失败", e);
            return JsonResult.fail("清除失败");
        }
    }

    /**
     * 从Session中获取当前用户
     */
    private LoginUserVO getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object userInfo = session.getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                return (LoginUserVO) userInfo;
            }
        }
        return null;
    }
} 